<template>
  <div class="security-container">
    <!-- 使用循环渲染安全项 -->
    <div v-for="item in securityItems" :key="item.field" class="security-item">
      <div class="security-info">
        <h3 class="security-title">{{ item.title }}</h3>
        <div class="security-detail">
          <template v-if="!isEditing[item.field]">
            <!-- 显示当前信息 -->
            <span v-html="item.display(current[item.field])"></span>
          </template>
          <template v-else>
            <!-- 编辑状态 -->
            <div class="edit-container">
              <input
                :type="
                  item.type === 'password'
                    ? showPassword
                      ? 'text'
                      : 'password'
                    : item.type
                "
                v-model="temp[item.field]"
                :placeholder="item.placeholder"
                @input="item.validate ? item.validate(temp[item.field]) : null"
              />
              <!-- 密码可见性切换 -->
              <span
                v-if="item.type === 'password'"
                class="toggle-password"
                @click="showPassword = !showPassword"
              >
                {{ showPassword ? "👁️" : "👁️🗨️" }}
              </span>
            </div>
            <!-- 错误提示 -->
            <div v-if="errors[item.field]" class="error-msg">
              {{ errors[item.field] }}
            </div>
          </template>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-container">
        <template v-if="!isEditing[item.field]">
          <button class="security-action" @click="startEditing(item.field)">
            {{ current[item.field] ? "修改" : "设置" }}
          </button>
        </template>
        <template v-else>
          <button class="save-btn" @click="save(item)">保存</button>
          <button class="cancel-btn" @click="cancelEditing(item.field)">
            取消
          </button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showPassword: false,
      errors: {},
      isEditing: {},
      temp: {},
      current: {
        password: "123456",
        phone: "13812345678",
        question: "",
        email: "123456@qq.com",
      },
      // 安全项配置
      securityItems: [],
    };
  },
  created() {
    this.securityItems = [
      {
        title: "账户密码",
        field: "password",
        type: "password",
        placeholder: "至少8位且包含字母、数字、符号",
        // 修改 display 函数
        display: (val) => {
          return val
            ? `当前密码强度：<span class="${this.getStrengthClass(
                val
              )}">${this.calculateStrength(val)}</span>`
            : "未设置密码";
        },
        validate: this.validatePassword,
      },
      {
        title: "密保手机",
        field: "phone",
        type: "tel",
        placeholder: "11位手机号码",
        display: (val) =>
          val ? `已绑定手机：${this.maskPhone(val)}` : "未绑定手机",
        validate: this.validatePhone,
      },
      {
        title: "密保问题",
        field: "question",
        type: "text",
        placeholder: "请输入密保问题",
        display: (val) => val || "未设置密保问题",
        validate: this.validateQuestion,
      },
      {
        title: "备用邮箱",
        field: "email",
        type: "email",
        placeholder: "请输入有效邮箱",
        display: (val) =>
          val ? `已绑定邮箱：${this.maskEmail(val)}` : "未绑定邮箱",
        validate: this.validateEmail,
      },
    ];
  },
  methods: {
    // 新增密码强度样式类方法
    getStrengthClass(password) {
      const strength = this.calculateStrength(password);
      return strength === "medium" ? "medium" : strength.toLowerCase();
    },
    // 启动编辑
    startEditing(field) {
      this.$set(this.isEditing, field, true);
      this.$set(this.temp, field, this.current[field]);
      this.$delete(this.errors, field);
    },

    // 取消编辑
    cancelEditing(field) {
      this.$set(this.isEditing, field, false);
      this.$set(this.temp, field, "");
    },

    // 保存数据
    async save(item) {
      if (item.validate && !(await item.validate(this.temp[item.field])))
        return;

      this.current[item.field] = this.temp[item.field];
      this.isEditing[item.field] = false;
      this.$message.success(`${item.title}更新成功`);

      // 这里可以调用API保存到后端
      console.log("保存数据:", item.field, this.temp[item.field]);
    },

    // 密码强度计算
    calculateStrength(password) {
      const rules = [/[a-z]/, /[A-Z]/, /\d/, /[\W_]/];
      const strength = rules.filter((rule) => rule.test(password)).length;

      if (!password || password.length < 8) return "weak";
      if (strength < 2) return "weak";
      if (strength === 2) return "medium";
      return "strong"; // 统一使用英文返回
    },

    // 验证方法
    validatePassword(pwd) {
      if (pwd.length < 8) {
        this.errors.password = "密码至少需要8位";
        return false;
      }
      // 修改判断条件为英文
      if (this.calculateStrength(pwd) === "weak") {
        this.errors.password = "密码强度不足";
        return false;
      }
      this.$delete(this.errors, "password");
      return true;
    },

    validatePhone(phone) {
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        this.errors.phone = "手机号码格式错误";
        return false;
      }
      this.$delete(this.errors, "phone");
      return true;
    },

    validateQuestion(question) {
      if (!question || question.trim().length === 0) {
        this.errors.question = "密保问题不能为空";
        return false;
      }
      this.$delete(this.errors, "question");
      return true;
    },

    validateEmail(email) {
      if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email)) {
        this.errors.email = "邮箱格式不正确";
        return false;
      }
      this.$delete(this.errors, "email");
      return true;
    },

    // 信息脱敏
    maskPhone(phone) {
      return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },

    maskEmail(email) {
      return email.replace(/(.{2}).+@(.+)/, (m, a, b) => `${a}****@${b}`);
    },
  },
};
</script>

<style scoped>
.security-container {
  max-width: 800px;
  margin: 24px auto;
  padding: 0 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.security-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.security-info {
  flex: 1;
  margin-right: 20px;
}

.security-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}

.security-detail {
  font-size: 14px;
  color: #5e6d82;
  line-height: 1.6;
}

.security-detail ::v-deep span.weak {
  color: #ff4d4f;
}
.security-detail ::v-deep span.medium {
  color: #faad14;
}
.security-detail ::v-deep span.strong {
  color: #52c41a;
}

.edit-container {
  position: relative;
  width: 280px;
}

.edit-container input {
  width: 100%;
  padding: 8px 36px 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s;
}

.edit-container input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
  outline: none;
}

.toggle-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  opacity: 0.6;
  transition: opacity 0.3s;
}

.toggle-password:hover {
  opacity: 1;
}

.error-msg {
  margin-top: 6px;
  font-size: 12px;
  color: #ff4d4f;
  padding-left: 4px;
  animation: shake 0.4s ease;
}

@keyframes shake {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(4px);
  }
  75% {
    transform: translateX(-4px);
  }
}

.action-container {
  flex-shrink: 0;
}

.security-action,
.save-btn,
.cancel-btn {
  min-width: 80px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.security-action {
  background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
  color: #1890ff;
  border: 1px solid #bae7ff;
}

.security-action:hover {
  background: linear-gradient(135deg, #e6f7ff, #d3effd);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.save-btn {
  background: linear-gradient(135deg, #409eff, #007bff);
  color: white;
  margin-right: 8px;
}

.save-btn:hover {
  opacity: 0.9;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.cancel-btn {
  background: linear-gradient(135deg, #f5f5f5, #eee);
  color: #606266;
}

.cancel-btn:hover {
  background: linear-gradient(135deg, #eee, #e5e5e5);
}

@media (max-width: 768px) {
  .security-item {
    flex-direction: column;
    align-items: stretch;
    padding: 16px;
  }

  .security-info {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .edit-container {
    width: 100%;
  }

  .action-container {
    display: flex;
    gap: 8px;
    margin-top: 12px;
  }

  .security-action,
  .save-btn,
  .cancel-btn {
    flex: 1;
    text-align: center;
  }
}
</style>
